package com.boc.langxiang.ui.activity.me;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.boc.langxiang.App;
import com.boc.langxiang.Constant;
import com.boc.langxiang.R;
import com.boc.langxiang.contract.ImageContract;
import com.boc.langxiang.contract.me.OrdersApplyRefundContract;
import com.boc.langxiang.entity.events.OrdersEvent;
import com.boc.langxiang.entity.response.OrderinfoReturnOrderPagesBean;
import com.boc.langxiang.presenter.ImagePresenter;
import com.boc.langxiang.presenter.me.OrdersApplyRefundPresenter;
import com.boc.langxiang.ui.adapter.me.OrdersApplyRefundRVAdapter;
import com.boc.langxiang.util.T;
import com.jakewharton.rxbinding.view.RxView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.loader.GlideImageLoader;
import com.lzy.imagepicker.ui.ImageGridActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class OrdersApplyRefundActivity extends MeBaseToolBarActivity implements OrdersApplyRefundContract.View, ImageContract.View {

    @BindView(R.id.tv_me_price)
    TextView tvMePrice;
    @BindView(R.id.recylerview)
    RecyclerView recylerview;
    @BindView(R.id.et_me_orders_apply)
    EditText etMeOrdersApply;
    @BindView(R.id.btn_me_set_exitlogin)
    Button btnMeSetExitlogin;
    private String mPrice;
    private List<ImageItem> mList;
    private OrdersApplyRefundRVAdapter mAdapter;
    private ImagePicker imagePicker;
    private boolean mIsOnActivityResult;
    private ArrayList<ImageItem> mTempImages;
    private OrdersApplyRefundPresenter mPresenter;
    private String mOrderId;
    private ImageContract.Presenter mImagePresenter;
    private int mImgCount = 0;
    List<String> mStringList;
    private String mGetContent;
    private String mGetStatus;
    private String mGetOrderId;
    private String mGetPay;
    private String mGetPrice;
    private boolean mIsImgSuccess;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders_apply_refund);
        ButterKnife.bind(this);
        setToolBarTitle("申请退款");
        mList = new ArrayList<>();
        Bundle extras = getIntent().getExtras();
        mPrice = extras.getString(Constant.ME_PRODUCT_TYPE_RETURN_PRICE, "");
        mOrderId = extras.getString(Constant.ME_PRODUCT_TYPE_RETURN_ID, "");
        tvMePrice.setText(mPrice);
        recylerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recylerview.setHasFixedSize(true);
        mAdapter = new OrdersApplyRefundRVAdapter(this, mList);
        recylerview.setAdapter(mAdapter);

        mStringList = new ArrayList<>();
        initEvent();
        mPresenter = new OrdersApplyRefundPresenter(this);
        mImagePresenter = new ImagePresenter(this);
        mPresenter.returnOrdersPage(mOrderId);

    }

    private void initEvent() {
        mAdapter.setOnImageClickListener(new OrdersApplyRefundRVAdapter.OnImageClickListener() {
            @Override
            public void onImageClick(View v, int position) {
            }

            @Override
            public void onAddClick(View v, int position) {
                if (mList.size() == 3) {
                    Toast.makeText(App.getInstance(), "请选删除一张图片再添加", Toast.LENGTH_SHORT).show();
                    return;
                }
                imagePick();
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onDeleteClick(View v, int position) {
                mList.remove(position);
                mStringList.remove(position);
                mAdapter.notifyDataSetChanged();
            }
        });

        RxView.clicks(btnMeSetExitlogin).throttleFirst(2, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {

                if (TextUtils.isEmpty(etMeOrdersApply.getText().toString())) {
                    Toast.makeText(App.getInstance(), "请输入退货原因", Toast.LENGTH_SHORT).show();
                    return;
                }
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < mStringList.size(); i++) {
                    sb.append(mStringList.get(i));
                    if (i != mStringList.size() - 1) {
                        sb.append(",");
                    }
                }
                mPresenter.returnOrdersPost(mOrderId, mGetContent, sb.toString(), etMeOrdersApply.getText().toString(), mGetPrice, mPrice, mGetPay, mGetStatus);
            }
        });
    }

    private void imagePick() {
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(GlideImageLoader.getInstance());
        imagePicker.setShowCamera(true);
        imagePicker.setSelectLimit(1);
        imagePicker.setCrop(false);
        Intent intent = new Intent(mContext, ImageGridActivity.class);
        startActivityForResult(intent, 99);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mIsOnActivityResult) {
            if (mImagePresenter == null) {
                mImagePresenter = new ImagePresenter(this);
            }
            mImagePresenter.uploadFile(mTempImages.get(0).path);

            mIsOnActivityResult = false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 99) {
                mTempImages = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            }
            mIsOnActivityResult = true;
        } else {
            T.showShort(mContext, "没有数据");
        }
    }


    @Override
    protected int setToolBarBackgroundColor() {
        return Color.WHITE;
    }

    @Override
    protected int setToolBarBackImg() {
        return R.drawable.icon_me_left;
    }

    @Override
    protected int setToolBarTitleColor() {
        return Color.BLACK;
    }


    @Override
    public void showLoading() {
        showProgressDialog("加载中，请稍后……");
    }

    @Override
    public void hideLoading() {
        hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        Toast.makeText(App.getInstance(), msg, Toast.LENGTH_SHORT).show();
        hideDialog();
    }

    @Override
    public void getReturnOrdersInfo(OrderinfoReturnOrderPagesBean orderinfo) {
        mGetContent = orderinfo.getContent();
        mGetStatus = orderinfo.getStatus();
        mGetOrderId = orderinfo.getOrderid();
        mGetPay = orderinfo.getPay();
        mGetPrice = orderinfo.getPrice();
    }

    @Override
    public void returnOrdersPostSuccess() {
        Toast.makeText(App.getInstance(), "申请退款成功", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(OrdersApplyRefundActivity.this, OrdersActivity.class);
        EventBus.getDefault().post(new OrdersEvent());
        OrdersApplyRefundActivity.this.startActivity(intent);
    }

    @Override
    public void uploadFileFailed() {
        Toast.makeText(App.getInstance(), "图片上传失败", Toast.LENGTH_SHORT).show();
        mIsImgSuccess = false;
    }

    @Override
    public void uploadFileSuccess(String content) {
        hideLoading();
        mStringList.add(content);
        mIsImgSuccess = true;
        mList.addAll(mTempImages);
        mAdapter.notifyDataSetChanged();
    }
}
